package de.tabuma.shopping.controller;

import de.tabuma.shopping.logik.*;
import de.tabuma.lib.tabumacontroller;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.google.appengine.api.users.*;

/**
 *
 * @author $Author: alefen $
 * @version $Revision: 1.2 $
 * @since $Date: 2009/07/21 19:37:32 $
 */
public class verificationOfPaymentController extends tabumacontroller {

    LicensePackageFacade licensePackageFacade;

    private static final Logger log = Logger.getLogger(verificationOfPaymentController.class.getName());
    String orderNav;
    public verificationOfPaymentController(String servlet, Hashtable parameter, String orderNav, LicensePackageFacade licensePackageFacade) {
        super(servlet, parameter);
        this.orderNav = orderNav;
        this.licensePackageFacade = licensePackageFacade;
    }


    public void navigate(ServletContext context, HttpServletRequest request, HttpServletResponse response, PrintWriter out)  {

        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        request.setAttribute(orderNav, de.tabuma.shopping.constants.ORDERNAV_VERIFICATIONPAYMENT);
        String orderToken = request.getParameter(de.tabuma.shopping.constants.ORDER_TOKEN);
        int orderID = OrderFacade.getOrderIDByToken(orderToken);
        String token = request.getParameter("token");
        if(orderToken==null) {
            request.setAttribute("noOrderTokenError", "true");
            return;
        }

        String payerID = PayPalFacade.getPayPalGetExpressCheckoutDetails(token,orderID);

        boolean result = true;
        if(payerID!=null) {
            result = PayPalFacade.getPayPalDoExpressCheckout(token,payerID,orderID, licensePackageFacade);
        }
        else {
            result = false;
        }

        if(result) {

            int ordernr = OrderFacade.setPayedForOrderByToken(orderToken,user.getEmail());
            if(ordernr==-1) {
                request.setAttribute("wrongOrderTokenError","true");
            }
            else {
                request.setAttribute(de.tabuma.shopping.constants.ORDER_NR, ""+ordernr);
            }
        }
        else {
            request.setAttribute("errorInConnectionWithPayPal","true");
        }


    }

}
